package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.constant.RedisConstants;
import com.hmdp.constant.UserConstant;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * LoginInterceptor
 * </p>
 *
 * @author flyduck
 * @since 2025/3/7
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 进入controller之前：1、将用户保存到ThreadLocal，刷新token
     * @param request
     * @param response
     * @param handler
     * @return true:继续处理请求   false:中断请求处理流程
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token，然后从根据token从redis获取用户
        String token = request.getHeader(UserConstant.TOKEN_HEADER);
        if (StrUtil.isBlank(token)) {
            return true;
        }
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(RedisConstants.RedisUserConstants.LOGIN_USER_KEY_PREFIX + token);
        if (userMap.isEmpty()) {
            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        //redis不存在用户，放行
        if (userDTO == null) {
            return true;
        }

        //保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);

        //给redis里面的token续期
        stringRedisTemplate.expire(RedisConstants.RedisUserConstants.LOGIN_USER_KEY_PREFIX + token,
                RedisConstants.RedisUserConstants.LOGIN_USER_TTL,
                TimeUnit.MINUTES);

        //放行
        return true;
    }

    /**
     * 在控制器方法执行之后，但在视图渲染之前调用。
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 视图渲染完成之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从ThreadLocal移除用户
        UserHolder.removeUser();
    }
}
